package com.itheima.stock.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.stock.mapper.SysPermissionMapper;
import com.itheima.stock.mapper.SysRoleMapper;
import com.itheima.stock.mapper.SysRolePermissionMapper;
import com.itheima.stock.pojo.domain.PermissionRespNodeVo;
import com.itheima.stock.pojo.entity.SysPermission;
import com.itheima.stock.pojo.entity.SysRole;
import com.itheima.stock.pojo.entity.SysRolePermission;
import com.itheima.stock.service.RolesService;
import com.itheima.stock.utils.IdWorker;
import com.itheima.stock.utils.ParsePerm;
import com.itheima.stock.vo.req.AddRolesAndPermsReqVo;
import com.itheima.stock.vo.req.UpdatePermsByRoleIdReqVo;
import com.itheima.stock.vo.resp.PageResult;
import com.itheima.stock.vo.resp.R;
import com.itheima.stock.vo.resp.ResponseCode;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * Description:角色业务层
 * Author:yuyang
 * Date:2024-05-02
 * Time:13:56
 */
@Service
@Slf4j
public class RolesServiceImpl implements RolesService {

    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Autowired
    private SysPermissionMapper sysPermissionMapper;

    @Autowired
    private SysRolePermissionMapper sysRolePermissionMapper;

    @Autowired
    private IdWorker idWorker;

    /**
     * 分页查询当前角色信息
     *
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public R<PageResult<SysRole>> getRolesPageInfo(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<SysRole> roleList = sysRoleMapper.selectAll();
        if (CollectionUtils.isEmpty(roleList)) {
            return R.error(ResponseCode.NO_RESPONSE_DATA.getMessage());
        }
        PageInfo<SysRole> pageInfo = new PageInfo<>(roleList);
        PageResult<SysRole> result = new PageResult<>(pageInfo);
        return R.ok(result);
    }

    /**
     * 树状结构回显权限集合,底层通过递归获取权限数据集合
     */
    @Override
    public R<List<PermissionRespNodeVo>> getPermissionsTreeAll() {
        List<SysPermission> permissionList = sysPermissionMapper.selectAll();
        if (CollectionUtils.isEmpty(permissionList)) {
            return R.error(ResponseCode.NO_RESPONSE_DATA.getMessage());
        }
        return R.ok(ParsePerm.recursion(permissionList, 0L));
    }

    /**
     * 添加角色和角色关联权限
     *
     * @param reqVo
     * @return
     */
    @Override
    public R addRolesAndPerms(AddRolesAndPermsReqVo reqVo) {
        SysRole role = SysRole.builder()
                .id(idWorker.nextId())
                .name(reqVo.getName())
                .description(reqVo.getDescription())
                .createTime(DateTime.now().toDate()).build();
        int i = sysRoleMapper.addRole(role);
        if (i > 0) {
            List<SysRolePermission> list = new ArrayList<>();
            for (Long permissionsId : reqVo.getPermissionsIds()) {
                list.add(SysRolePermission.builder()
                        .id(idWorker.nextId())
                        .roleId(role.getId())
                        .permissionId(permissionsId)
                        .createTime(DateTime.now().toDate()).build());
            }
            int j = sysRolePermissionMapper.insertPerms(list);
            if (j > 0) {
                return R.ok("操作成功");
            }
        }
        return R.error(ResponseCode.NO_RESPONSE_DATA.getMessage());
    }

    /**
     * 根据角色id查询权限
     *
     * @param roleId
     * @return
     */
    @Override
    public R<List<Long>> getPermsByRoleId(String roleId) {
        List<Long> perms = sysRolePermissionMapper.getPermsByRoleId(roleId);
        if (perms != null) {
            return R.ok(perms);
        }
        return R.error(ResponseCode.DATA_ERROR.getMessage());
    }

    /**
     * 添加角色和角色关联权限
     *
     * @param reqVo
     * @return
     */
    @Override
    public R updatePermsByRoleId(UpdatePermsByRoleIdReqVo reqVo) {
        List<Long> perms = sysRolePermissionMapper.getPermsByRoleId(String.valueOf(reqVo.getId()));
        if (!CollectionUtils.isEmpty(perms)) {
            int i = sysRolePermissionMapper.deleteByRoleId(reqVo.getId());
            if (i <= 0) {
                return R.error(ResponseCode.DATA_ERROR.getMessage());
            }
        }
        List<SysRolePermission> rolePermissions = new ArrayList<>();
        for (Long permissionsId : reqVo.getPermissionsIds()) {
            rolePermissions.add(SysRolePermission.builder()
                    .id(idWorker.nextId())
                    .roleId(reqVo.getId())
                    .permissionId(permissionsId)
                    .createTime(DateTime.now().toDate()).build());
        }
        int j = sysRolePermissionMapper.insertPerms(rolePermissions);
        if (j > 0) {
            return R.ok("操作成功");
        } else return R.error(ResponseCode.DATA_ERROR.getMessage());
    }

    /**
     * 根据角色id删除角色信息
     *
     * @param roleId
     * @return
     */
    @Override
    public R deleteRoles(String roleId) {
        int i = sysRoleMapper.deleteRole(roleId);
        if (i > 0) {
            return R.ok("删除成功");
        } else return R.error(ResponseCode.DATA_ERROR.getMessage());
    }

    /**
     * 更新用户的状态信息
     *
     * @param roleId
     * @param status
     * @return
     */
    @Override
    public R updateRoleStatus(String roleId, Integer status) {
        int i = sysRoleMapper.updateRoleStatus(roleId, status);
        if (i > 0) {
            return R.ok("操作成功");
        } else return R.error(ResponseCode.DATA_ERROR.getMessage());
    }
}